<template>
  <a-modal
    :width="1000"
    :visible="visible"
    title="温度模式调度数据"
    :body-style="{ backgroundColor: '#F0F2F5', padding: '8px' }"
    :footer="null"
    @update:visible="updateVisible"
  >
    <div class="ele-body">
      <!-- 表格 -->
      <div>
        <a-card :bordered="false">
          <ele-pro-table
            ref="table"
            row-key="sctttId"
            :datasource="datasource"
            :columns="columns"
            :where="where"
            :scroll="{ x: 'max-content' }"
          >
          </ele-pro-table>
        </a-card>
      </div>
    </div>
  </a-modal>

  <!-- JSON查看弹窗 -->
  <a-modal
    v-model:visible="jsonModalVisible"
    :title="jsonModalTitle"
    width="1000px"
    :footer="null"
  >
    <a-card :bordered="false">
      <template v-if="jsonModalTitle === '时间分配结果'">
        <div class="time-strategy-title">分区时间段划分：</div>
        <div v-for="(times, region) in jsonData.time_strategy" :key="region" class="time-strategy-item">
          <div class="region-title">分区 {{ region }}:</div>
          <a-collapse>
            <a-collapse-panel 
                :key="region" 
                :header="getTimeStrategyHeader(times, region, jsonData.time_slot_version)"
              >
              <a-table
                :dataSource="formatTimeStrategy(times)"
                :columns="timeStrategyColumns"
                size="small"
                :pagination="false"
              />
            </a-collapse-panel>
          </a-collapse>
        </div>

        <div class="time-strategy-title">分区时间点划分：</div>
        <div v-for="(times, region) in jsonData.dahua_time_strategy" :key="region" class="time-strategy-item">
          <div class="region-title">分区 {{ region }}:</div>
          <a-collapse>
            <a-collapse-panel 
                :key="region" 
                :header="getTimeStrategyHeader(times, region, jsonData.time_slot_version)"
              >
              <a-table
                :dataSource="formatDahuaTimeStrategy(times)"
                :columns="dahuatTimeStrategyColumns"
                size="small"
                :pagination="false"
              />
            </a-collapse-panel>
          </a-collapse>
        </div>
      </template>
      <template v-else>
        <pre class="json-viewer">{{ formatJson(jsonData) }}</pre>
      </template>
    </a-card>
  </a-modal>
</template>

<script>
import {
  DeviceSprayCameraTimerangeTemprangeApi
} from "@/api/property/spraycamera/DeviceSprayCameraTimerangeTemprangeApi";
import { message } from 'ant-design-vue';
import { h } from 'vue';

export default {
  name: 'DeviceManagerdeviceCameraGroupmanagerTimerangeTemprange',
  components: {
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 菜单数据
    data: Object
  },
  async mounted() {
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '时间段',
          dataIndex: 'timerange'
        },
        {
          title: '温度区间',
          dataIndex: 'temprange',
          customRender: ({ text }) => {
            if (!text) return '-';
            const [min, max] = text.split('-').map(v => (Number(v) / 10).toFixed(1));
            return `${min}-${max}`;
          }
        },
        {
          title: '是否删除',
          dataIndex: 'isDelete',
          customRender : function(row) {
            if (row.text == 1) {
              return "已删除";
            } else {
              return "未删除";
            }
          },
        },
        {
          title: '是否生效',
          dataIndex: 'tempModeStatus',
          customRender : function(row) {
            if (row.text == 1) {
              return "生效中";
            } else {
              return "未生效";
            }
          },
        },
        {
          title: '温度达标次数统计',
          dataIndex: 'calcount'
        },
        {
          title: '温度达标次数统计时间',
          dataIndex: 'calcountUpdateTime'
        },
        {
          title: '时间分配结果',
          dataIndex: 'tempModeResult',
          ellipsis: true,
          customRender: ({ text }) => {
            return h('a', {
              onClick: () => this.viewJsonData('时间分配结果', text)
            }, text ? '查看详情' : '-');
          }
        },
      ],
      // 表格搜索条件
      where: {
        logId : this.data.scsclId
      },
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
       // ... 其他数据项
       jsonModalVisible: false,
      jsonModalTitle: '',
      jsonData: {},
      timeStrategyColumns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
        },
        {
          title: '开始时间',
          dataIndex: 'start',
          width: 150,
        },
        {
          title: '结束时间',
          dataIndex: 'end',
          width: 150,
        },
        {
          title: '时长',
          dataIndex: 'duration',
        }
      ],
      dahuatTimeStrategyColumns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
        },
        {
          title: '开始时间',
          dataIndex: 'start',
          width: 150,
        },
        {
          title: '执行时长',
          dataIndex: 'runduration',
          width: 150,
        },
        {
          title: '等待时长',
          dataIndex: 'waitduration',
        }
      ],
    };
  },
  methods: {
    getTimeStrategyHeader(times, region, versionInfo) {
      let header = `时间段列表（${times.length}个）`;
      if (versionInfo && versionInfo[region]) {
        header += ` - 版本号：${versionInfo[region]}`;
      }
      return header;
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    reset() {
      this.where.logId  = this.data.scsclId;
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    async remove(row) {
      const result = await DeviceSprayCameraTimerangeTemprangeApi.delete({ sctttId: row.sctttId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    datasource({ page, limit, where, orders }) {
      return DeviceSprayCameraTimerangeTemprangeApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    viewJsonData(title, jsonStr) {
      this.jsonModalTitle = title;
      try {
        this.jsonData = JSON.parse(jsonStr || '{}');
      } catch (e) {
        this.jsonData = jsonStr || '';
      }
      this.jsonModalVisible = true;
    },

    formatJson(json) {
      try {
        return JSON.stringify(json, null, 2);
      } catch (e) {
        return json;
      }
    },

    formatTimeStrategy(times) {
      return times.map((time, index) => ({
        key: index,
        index: index + 1,
        start: time[0],
        end: time[1],
        duration: this.calculateDuration(time[0], time[1])
      }));
    },

    calculateDuration(start, end) {
      const startParts = start.split(':').map(Number);
      const endParts = end.split(':').map(Number);
      const startSeconds = startParts[0] * 3600 + startParts[1] * 60 + startParts[2];
      const endSeconds = endParts[0] * 3600 + endParts[1] * 60 + endParts[2];
      const durationSeconds = endSeconds - startSeconds;
      return `${durationSeconds}秒`;
    },

    formatDahuaTimeStrategy(times) {
      return times.map((time, index) => ({
        key: index,
        index: index + 1,
        start: time[0],
        runduration: `${time[1]}秒`,
        waitduration: `${time[2]}秒`,
      }));
    },

  }
};
</script>

<style scoped>
.json-viewer {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  max-height: 500px;
  overflow: auto;
  font-family: 'Courier New', Courier, monospace;
  white-space: pre-wrap;
  word-break: break-all;
}

.time-strategy-item {
  margin-bottom: 20px;
}

.region-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.time-strategy-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
}
</style>
